package com.ctshk.rpc.user.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDefaultCode;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.Assert;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.train.dto.ReservationTrainPageDTO;
import com.ctshk.rpc.user.dto.PassengerCertificatesDTO;
import com.ctshk.rpc.user.dto.PassengerDTO;
import com.ctshk.rpc.user.dto.PassengerListDTO;
import com.ctshk.rpc.user.entity.Passenger;
import com.ctshk.rpc.user.entity.PassengerCertificates;
import com.ctshk.rpc.user.entity.User;
import com.ctshk.rpc.user.entity.UserReceivingAddress;
import com.ctshk.rpc.user.mapper.PassengerCertificatesMapper;
import com.ctshk.rpc.user.mapper.PassengerMapper;
import com.ctshk.rpc.user.req.BatchDeleteReq;
import com.ctshk.rpc.user.req.PassengerCertificatesReq;
import com.ctshk.rpc.user.req.PassengerPageReq;
import com.ctshk.rpc.user.req.PassengerReq;
import com.ctshk.rpc.user.service.IPassengerService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *
 * </p>
 *
 * @author 李新科
 * @date 2021/5/17 11:28
 */
@DubboService
public class PassengerServiceImpl extends ServiceImpl<PassengerMapper, Passenger> implements IPassengerService {

    @Autowired
    private PassengerMapper passengerMapper;

    @Autowired
    private PassengerCertificatesMapper passengerCertificatesMapper;

    @Override
    public Result<PageResponse<PassengerListDTO>> queryPage(PassengerPageReq req) {
        Page<Passenger> page = new Page(req.getPageNo(), req.getPageSize());
        Page<Passenger> passengerPage = passengerMapper.selectPage(page, new QueryWrapper<Passenger>()
                .lambda().eq(Passenger::getUserId, req.getUserId())
        .eq(Passenger::getIsDeleted, IsDeletedCode.NO.getCode()));


        List<PassengerListDTO> passengerListDTOS = EntityUtil.copyList(passengerPage.getRecords(), PassengerListDTO.class);
        passengerListDTOS.stream().forEach(passengerListDTO -> {
            Long id = passengerListDTO.getId();
            List<PassengerCertificates> passengerCertificatesList = passengerCertificatesMapper.selectList(Wrappers.<PassengerCertificates>lambdaQuery().eq(PassengerCertificates::getUserPassengerId, id));
            StringJoiner sj = new StringJoiner(" ");
            if(!CollectionUtils.isEmpty(passengerCertificatesList)) {
                for (int i = 0; i < passengerCertificatesList.size(); i++) {
                    PassengerCertificates passengerCertificates = passengerCertificatesList.get(i);
                    if(i == 0) {
                        passengerListDTO.setFirstCertificatesTypeName(passengerCertificates.getCertificatesTypeName());
                        passengerListDTO.setCertificatesNumber(passengerCertificates.getCertificatesNumber());
                    }
                    if(i > 3) {
                        sj.add("......");
                        break;
                    }
                    sj.add(passengerCertificates.getCertificatesTypeName());

                    /*if(StringUtils.isNotBlank(certificatesNumber)) {
                        if(certificatesNumber.length() < 6) {
                            passengerListDTO.setCertificatesNumber("******");
                        } else {
                            int length = certificatesNumber.length();
                            passengerListDTO.setCertificatesNumber(certificatesNumber.substring(0,2) + generateSymbol("*",length - 4) + certificatesNumber.substring(length - 2));
                        }
                    }*/
                }
                passengerListDTO.setCertificatesTypeName(sj.toString());
            }

        });

        PageResponse<PassengerListDTO> result = new PageResponse<>(passengerListDTOS,
                passengerPage.getCurrent() == 1, passengerPage.getTotal() <= (passengerPage.getCurrent() *
                passengerPage.getSize()), passengerPage.getTotal(), passengerPage.getCurrent(), passengerPage.getSize());
        return Result.success(result);
    }

    private String generateSymbol(String symbolStr,int num) {
        StringBuffer sb = new StringBuffer();
        if(symbolStr != null) {
            for (int i = 0; i < num; i++) {
                sb.append(symbolStr);
            }
        }
        return sb.toString();
    }


    @Override
    public Result add(PassengerReq req) {

        Long userId = req.getUserId();
        Integer count = passengerMapper.selectCount(Wrappers.<Passenger>lambdaQuery()
                .eq(Passenger::getUserId, userId)
                .eq(Passenger::getIsDeleted, IsDeletedCode.NO.getCode()));

        if(count == 20) {
            throw new BusinessException(SystemError.SYS_433,"常用旅客最多添加20个");
        }

        List<PassengerCertificatesReq> passengerCertificatesReqList = req.getPassengerCertificatesList();
        if(!CollectionUtils.isEmpty(passengerCertificatesReqList)) {
            if(passengerCertificatesReqList.size() >= 3) {
                throw new BusinessException(SystemError.SYS_433,"证件最多添加3个");
            }
        }

        Set<String> certificateSet = new HashSet<>();
        StringJoiner sj = new StringJoiner(",");
        for (PassengerCertificatesReq passengerCertificatesReq : passengerCertificatesReqList) {
            String s = passengerCertificatesReq.getCertificatesTypeName() + passengerCertificatesReq.getCertificatesNumber();
            boolean contains = certificateSet.contains(s);
            if(contains) {
                sj.add(passengerCertificatesReq.getCertificatesTypeName() + passengerCertificatesReq.getCertificatesNumber());
            } else {
                certificateSet.add(s);
            }
        }
        if(sj.length() > 0) {
            throw new BusinessException(SystemError.USER_1027,sj.toString());
        }

        long id = SnowflakeIdWorker.nextId();
        LocalDateTime now = LocalDateTime.now();
        Passenger passenger = EntityUtil.copy(req, Passenger.class);
        passenger.setUserId(userId);

        passenger.setId(id);
        passenger.setCreateId(userId);
        passenger.setGmtCreate(now);
        passenger.setGmtModified(now);
        passenger.setEnFullname(passenger.getEnSurname() + passenger.getEnName());
        passenger.setIsDeleted(IsDeletedCode.NO.getCode());
        passengerMapper.insert(passenger);

        List<PassengerCertificates> passengerCertificatesList = EntityUtil.copyList(passengerCertificatesReqList, PassengerCertificates.class);
        if(!CollectionUtils.isEmpty(passengerCertificatesList)) {
            passengerCertificatesList.stream().forEach(passengerCertificates -> {
                long passengerCertificatesId = SnowflakeIdWorker.nextId();
                passengerCertificates.setCreateId(userId);
                passengerCertificates.setGmtCreate(now);
                passengerCertificates.setGmtModified(now);
                passengerCertificates.setUserPassengerId(id);
                passengerCertificates.setId(passengerCertificatesId);
                passengerCertificates.setIsDeleted(IsDeletedCode.NO.getCode());
            });
            passengerCertificatesMapper.insertBatchSomeColumn(passengerCertificatesList);
        }
        return Result.success();
    }

    @Override
    public Result update(PassengerReq req) {
        Assert.nonNull(req.getId(), SystemError.SYS_412);
        List<PassengerCertificatesReq> passengerCertificatesReqList = req.getPassengerCertificatesList();
        if(!CollectionUtils.isEmpty(passengerCertificatesReqList)) {
            if(passengerCertificatesReqList.size() >= 3) {
                throw new BusinessException(SystemError.SYS_433,"证件最多添加3个");
            }
        }
        Set<String> certificateSet = new HashSet<>();
        StringJoiner sj = new StringJoiner(",");
        for (PassengerCertificatesReq passengerCertificatesReq : passengerCertificatesReqList) {
            String s = passengerCertificatesReq.getCertificatesTypeName() + passengerCertificatesReq.getCertificatesNumber();
            boolean contains = certificateSet.contains(s);
            if(contains) {
                sj.add(passengerCertificatesReq.getCertificatesTypeName() + passengerCertificatesReq.getCertificatesNumber());
            } else {
                certificateSet.add(s);
            }
        }

        if(sj.length() > 0) {
            throw new BusinessException(SystemError.USER_1027,sj.toString());
        }
        Long id = req.getId();
        LocalDateTime now = LocalDateTime.now();
        Long userId = req.getUserId();
        Passenger passenger = EntityUtil.copy(req, Passenger.class);
        passenger.setEnFullname(passenger.getEnSurname() + passenger.getEnName());
        passenger.setUserId(userId);
        passenger.setModifiedId(userId);
        passenger.setGmtModified(now);
        passengerMapper.update(passenger,new UpdateWrapper<Passenger>().lambda().eq(Passenger::getId, req.getId()));

        passengerCertificatesMapper.deleteByUserPassengerId(id);
        List<PassengerCertificates> passengerCertificatesList = EntityUtil.copyList(passengerCertificatesReqList, PassengerCertificates.class);
        if(!CollectionUtils.isEmpty(passengerCertificatesList)) {
            passengerCertificatesList.stream().forEach(passengerCertificates -> {
                long passengerCertificatesId = SnowflakeIdWorker.nextId();
                passengerCertificates.setCreateId(userId);
                passengerCertificates.setGmtCreate(now);
                passengerCertificates.setGmtModified(now);
                passengerCertificates.setUserPassengerId(id);
                passengerCertificates.setId(passengerCertificatesId);
                passengerCertificates.setIsDeleted(IsDeletedCode.NO.getCode());
            });
            passengerCertificatesMapper.insertBatchSomeColumn(passengerCertificatesList);
        }

        return Result.success();
    }

    @Override
    public Result delete(Long id, Long userId) {
        passengerCertificatesMapper.delete(new QueryWrapper<PassengerCertificates>()
                .lambda().eq(PassengerCertificates::getUserPassengerId, id)
        .eq(PassengerCertificates::getCreateId, userId));
        passengerMapper.delete(new QueryWrapper<Passenger>()
                .lambda().eq(Passenger::getId, id)
                .eq(Passenger::getCreateId, userId));
        return Result.success();
    }

    @Override
    public Result batchDelete(BatchDeleteReq req) {
        passengerMapper.deleteBatchIds(req.getIds());
        return Result.success();
    }

    @Override
    public Result<PassengerDTO> detail(Long id, Long userId) {
        PassengerDTO passengerDTO = null;
        Passenger passenger = passengerMapper.selectOne(new QueryWrapper<Passenger>()
                .lambda().eq(Passenger::getId, id)
                .eq(Passenger::getUserId, userId)
                .eq(Passenger::getIsDeleted, IsDeletedCode.NO.getCode()));

        // 查询证件资料
        if(passenger != null) {
            List<PassengerCertificatesDTO> passengerCertificatesDTOS = new ArrayList<>();
            passengerDTO = EntityUtil.copy(passenger,PassengerDTO.class);
            List<PassengerCertificates> passengerCertificates = passengerCertificatesMapper.selectList(new QueryWrapper<PassengerCertificates>()
                    .lambda().eq(PassengerCertificates::getUserPassengerId, passenger.getId())
                    .eq(PassengerCertificates::getCreateId, userId)
                    .eq(PassengerCertificates::getIsDeleted, IsDeletedCode.NO.getCode()));
            if(!CollectionUtils.isEmpty(passengerCertificates)) {
                passengerCertificatesDTOS = EntityUtil.copyList(passengerCertificates, PassengerCertificatesDTO.class);
            }
            passengerDTO.setPassengerCertificatesList(passengerCertificatesDTOS);
        }

        return Result.success(passengerDTO);
    }

    @Override
    public Result setDefault(Long id, Long userId,Integer isDefault) {
        Passenger entity = new Passenger();
        entity.setIsDefault(IsDefaultCode.NO.getCode());
        if(isDefault == 1) {
            passengerMapper.update(entity,new UpdateWrapper<Passenger>()
                    .lambda().eq(Passenger::getUserId, userId));
            entity.setIsDefault(IsDefaultCode.YES.getCode());
            passengerMapper.update(entity,new UpdateWrapper<Passenger>()
                    .lambda().eq(Passenger::getId, id));
        } else {
            passengerMapper.update(entity,new UpdateWrapper<Passenger>()
                    .lambda().eq(Passenger::getId, id));
        }
        return Result.success();
    }
}
